/**
 * @param {WebGLRenderingContext} gl
 */
function createShader(gl, type, source) {
  const shader = gl.createShader(type);
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  return shader;
}

const vsSource = /*glsl*/ `
  precision mediump float;
  attribute vec2 a_Position;
  // canvas的大小
  attribute vec2 a_Screen_Size;

  void main() {
    // 将屏幕坐标系转化为裁剪坐标
    vec2 position = (a_Position / a_Screen_Size) * 2.0 - 1.0;
    position = position * vec2(1.0, -1.0);
    gl_Position = vec4(position, 0.0, 1.0); 
  }
`;

const fsSource = /*glsl*/ `
  precision mediump float;

  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }
`;

/**
 * @type {HTMLCanvasElement}
 */
const canvas = document.getElementById('canvas');
/**
 * @type {WebGLRenderingContext} gl
 */
const gl = canvas.getContext('webgl');
const vShader = createShader(gl, gl.VERTEX_SHADER, vsSource);
const fShader = createShader(gl, gl.FRAGMENT_SHADER, fsSource);

const program = gl.createProgram();
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
gl.linkProgram(program);
gl.useProgram(program);

const aPosition = gl.getAttribLocation(program, 'a_Position');
const uColor = gl.getUniformLocation(program, 'u_Color');
const aScreenSize = gl.getAttribLocation(program, 'a_Screen_Size');
gl.vertexAttrib2f(aScreenSize, canvas.width, canvas.height);

// 使用缓冲区来存储数据
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.enableVertexAttribArray(aPosition);
gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);

const points = [];
canvas.addEventListener('click', (e) => {
  points.push(e.pageX, e.pageY);
  if (points.length % 2 === 0) {
    // 从缓冲区读数据，绘制图形
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(points), gl.DYNAMIC_DRAW);
    gl.clearColor(0, 0, 0, 1);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.LINE_LOOP, 0, points.length / 2);
  }
});

gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
